﻿using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using WinRT;
using WPFTools;
using Path = System.IO.Path;

namespace CSharpToolWPF.Pages {
    /// <summary>
    /// PageTest.xaml 的交互逻辑
    /// </summary>
    public partial class PageTest : Page {
        private static PageTest page;
        public static PageTest Instance {
            get;
            set;
        }
        private VCXXmlTools vcxXmlTools = null;
        private VCXmlTools vcXmlTools = null;
        private TaskCompletionSource<bool> taskCompletionSource = new();
        public class ClassAndLibData {
            public ClassAndLibData(string className, string libName) {
                ClassName = className;
                LibName = libName;
            }
            public string ClassName { get; set; }
            public string LibName { get; set; }
        }
        private ObservableCollection<ClassAndLibData> listClassAndLib = null;
        private string listSavePath = "./Data/ClassAndLibList.json";
        private FontFamily fontSarasa = new FontFamily("Sarasa Term SC");
        private string basePath = "D:/VC/ObjectPRX 2024/sln/";
        public PageTest() {
            InitializeComponent();
            this.KeepAlive = true;
            Instance = this;
            // 
            
            vcxXmlTools = new(rtbLog);
            vcXmlTools = new(rtbLog);

            rtbLog.TextChanged += rtbLog_TextChanged;

            this.FontFamily = fontSarasa;
        }


        private void btnTranferLibsFromVCX2VC_Click(object sender, RoutedEventArgs e) {
            //var listProjectDirectoryPaths = CommonFunc.GetFilePathListFromDragInRTB(rtbFileList, "*.vcxproj");
            //foreach (var path in listProjectDirectoryPaths) {
            //    var xmlDoc = new XmlDocument();
            //    xmlDoc.Load(path);
            //    // 
            //    var listLibsInVCX = vcxXmlTools.GetOriginalInputLibsList
            //    var listLibsInVC = vcXmlTools.GetInputLibs()
            //}
            MessageBox.Show("未实现。");
        }

        private async void btnStart_Click(object sender, RoutedEventArgs e) {
            string pattern = tbLibToRemove.Text;
            string content = new TextRange(rtbFileList.Document.ContentStart, rtbFileList.Document.ContentEnd).Text;
            var matches = Regex.Matches(content, pattern, RegexOptions.Multiline);
            rtbLog.AppendText("\n");
            //foreach (Match item in matches) {
            //    foreach (Group group in item.Groups) {
            //        rtbLog.AppendText(group.Value + "\n");
            //    }
            //    rtbLog.AppendText("\n");
            //}
            rtbLog.AppendText(matches[0].Groups["FullName"].Value);

            return;
            //rtbLog.AppendText("123");
            //return;
            //btnStart.IsEnabled = false;
            List<string> filePathList = new List<string>();
            foreach (Block blk in rtbFileList.Document.Blocks) {
                var para = blk as Paragraph;
                if (para == null) {
                    continue;
                }
                var run = para.Inlines.ElementAt(0) as Run;
                if (run == null) {
                    continue;
                }
                filePathList.Add(run.Text);
            }
            //foreach (var item in filePathList) {
            //    rtbLog.AppendText(Path.GetFileName(item)+";");
            //}
            //return;
            // Key为项目名，带编号，Value为log文件路径
            var listProjectFile = new List<KeyValuePair<string, string>>();
            foreach (string path in filePathList) {
                if (!Directory.Exists(path)) {
                    continue;
                }
                string projectName = Path.GetFileName(path);
                string projectFilePath = $"{path}/{projectName}.vcxproj";
                if (!File.Exists(projectFilePath)) {
                    Logger.WriteLog($"没有找到项目 {projectName} ！\n", rtbLog, Colors.Yellow);
                    continue;
                }
                listProjectFile.Add(new KeyValuePair<string, string>(projectName, projectFilePath));
            }
            
            
        }
        private void rtbFileList_DragEnter(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                e.Effects = DragDropEffects.Copy;
            }
            else
                e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void tbSlnPath_Drop(object sender, DragEventArgs e) {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
                // 获取文件路径数组
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                // 清空 RichTextBox 内容
                rtbFileList.Document.Blocks.Clear();

                // 遍历文件路径并显示在 RichTextBox 中
                foreach (var file in files) {
                    Paragraph paragraph = new Paragraph(new Run(file));
                    rtbFileList.Document.Blocks.Add(paragraph);
                }
            }
        }

        private void btnContinue_Loaded(object sender, RoutedEventArgs e) {
            btnContinue.Visibility = Visibility.Collapsed;
        }

        private void btnContinue_Click(object sender, RoutedEventArgs e) {
            taskCompletionSource.SetResult(true);
            btnContinue.Visibility = Visibility.Collapsed;
            btnStart.IsEnabled = true;
        }

        private void btnNewLine_Click(object sender, RoutedEventArgs e) {
            listClassAndLib.Add(new ClassAndLibData("", ""));
        }

        private void btnSaveList_Click(object sender, RoutedEventArgs e) {
            string json = JsonConvert.SerializeObject(listClassAndLib, Newtonsoft.Json.Formatting.Indented);
            if (!Directory.Exists("./Data")) {
                Directory.CreateDirectory("./Data");
            }
            File.WriteAllText(this.listSavePath, json);
        }

        private void btnTest_Click(object sender, RoutedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //this.Height = window.MainFrame.ActualHeight;
        }

        private void rtbLog_TextChanged(object sender, TextChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //rtbLog.Height = (window.MainFrame.ActualHeight - 125) / 2 - 2;
            rtbLog.ScrollToEnd();
        }

        private void ListClassAndLib_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //datagridClassLib.Height = (window.MainFrame.ActualHeight - 125) / 2 - 2;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e) {
            rtbLog_TextChanged(null, null);
            ListClassAndLib_CollectionChanged(null, null);
            rtbFileList_TextChanged(null, null);
        }

        private void rtbFileList_TextChanged(object sender, TextChangedEventArgs e) {
            var window = Window.GetWindow(this) as MainWindow;
            if (window == null) {
                return;
            }
            //rtbFileList.Height = (window.MainFrame.ActualHeight - 125) - 2;
        }

        private void btnClearLog_Click(object sender, RoutedEventArgs e) {
            rtbLog.Document.Blocks.Clear();
        }

        private void btnDeleteAllReferences_Click(object sender, RoutedEventArgs e) {
            var pathList = CommonFunc.GetPathListFromDragInRTB(rtbFileList);
            foreach (var path in pathList) {
                if (!Path.Exists(path)) {
                    continue;
                }
                if(checkBoxIsNewProject.IsChecked == true) {
                    var vcxFilePaths = Directory.GetFiles(path, "*.vcxproj");
                    if (vcxFilePaths.Length == 0) {
                        continue;
                    }

                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(vcxFilePaths[0]);
                    vcxXmlTools.RemoveAllDependencies(xmlDoc, true);
                    xmlDoc.Save(vcxFilePaths[0]);
                }
                else {
                    var vcFilePaths = Directory.GetFiles(path, "*.vcproj");
                    if (vcFilePaths.Length == 0) {
                        continue;
                    }

                    string projectFilePath = vcFilePaths[0];
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(vcFilePaths[0]);
                    var inputLibsNode = vcXmlTools.GetInputLibsNode(xmlDoc);
                    if (inputLibsNode == null) {
                        Logger.WriteLog($"项目 {projectFilePath} 未成功获取到输入库节点！\n", rtbLog, Colors.Red);
                    }
                    inputLibsNode.InnerText = "";
                    vcXmlTools.SaveInGB2312(xmlDoc, projectFilePath);
                }

            }

        }

        private void btnDeleteSpecifiedLib_Click(object sender, RoutedEventArgs e) {
            var listProjectFile = CommonFunc.GetFilePathListFromDragInRTB(rtbFileList, "*.vcxproj");
            if (listProjectFile.Count == 0) {
                Logger.WriteLog($"没有能够修改的项目！\n", rtbLog, Colors.Yellow);
                return;
            }
            foreach (var filePath in listProjectFile) {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);
                // 
                if (checkBoxIsNewProject.IsChecked == true) {
                    if (vcxXmlTools.RemoveDependencies(xmlDoc, tbLibToRemove.Text)) {
                        Logger.WriteLog($"项目 {filePath} 已删除依赖项 {tbLibToRemove.Text}！\n", rtbLog, Colors.Green);
                    }
                    if (vcxXmlTools.RemoveInputLibs(xmlDoc, tbLibToRemove.Text, isDebug: true)) {
                        Logger.WriteLog($"项目 {filePath} 已删除输入库 {tbLibToRemove.Text}！\n", rtbLog, Colors.Green);
                    }
                    Logger.WriteLog($"\n", rtbLog, Colors.Yellow);
                }
                else {
                    var inputLibsNode = vcXmlTools.GetInputLibsNode(xmlDoc, isDebug: true);
                    if (inputLibsNode == null) {
                        Logger.WriteLog($"项目 {filePath} 未成功获取到输入库节点！\n", rtbLog, Colors.Red);
                        continue;
                    }
                    MessageBox.Show("错误：未实现！");
                }
                xmlDoc.Save(filePath);

            }
        }
    }
}
